/**
 * 
 */
package com.asset.salesforce.controller.pages;

import java.util.Locale;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.dto.UserDTO;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.UserShiroService;

// TODO: Auto-generated Javadoc
/**
 * The Class LoginController.
 *
 * @author Hisham
 */
@Controller
public class LoginController {

	/** The user shiro service. */
	@Autowired
	private UserShiroService userShiroService;

	/** The employee service. */
	@Autowired
	private EmployeeService employeeService;
	
	/** The application context. */
	@Autowired
	private ApplicationContext applicationContext;
	
	/**
	 * Gets the login page.
	 *
	 * @param model the model
	 * @return the login page
	 */
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String getLoginPage(Model model){
		model.addAttribute("loginDTO",new UserDTO());
		return "login";
	}
	
	/**
	 * Post login.
	 *
	 * @param session the session
	 * @param dto the dto
	 * @param result the result
	 * @param model the model
	 * @return the string
	 */
	@RequestMapping(value = "/login",method=RequestMethod.POST)
	public String postLogin(HttpSession session,@Valid @ModelAttribute("loginDTO") UserDTO dto,BindingResult result,Model model) {
		String forword = "";
		Employee user = employeeService.getByEmailAndPassword(dto.getEmail(), dto.getPassword());
		if(user!=null){
			boolean isActive = user.getIsActive();
			boolean isOwner = user.getIsOwner();
			boolean isFirstLogin = user.getFirstLogin();
			if (!isOwner && !isActive) {
				String errorMessage = applicationContext.getMessage("loginError", null, Locale.getDefault());
				result.reject(errorMessage, errorMessage);
				model.addAttribute("result", result);
				forword = "login";
			}
			else if (isActive && isFirstLogin){
				user.setFirstLogin(false);
				employeeService.saveOrupdate(user);
				UsernamePasswordToken token = new UsernamePasswordToken(dto.getEmail(),dto.getPassword(), false);
				try {
					SecurityUtils.getSubject().login(token);
					session.setAttribute("userDetails", user);
					forword = "redirect:start";
				} catch (AuthenticationException e) {
					String errorMessage = applicationContext.getMessage("loginError", null, Locale.getDefault());
					result.reject(errorMessage, errorMessage);
					model.addAttribute("result", result);
					forword = "login";
					e.printStackTrace();

				}
			}
		 else if (isActive && !isFirstLogin) {
			UsernamePasswordToken token = new UsernamePasswordToken(dto.getEmail(),dto.getPassword(), false);
			try {
				SecurityUtils.getSubject().login(token);
				session.setAttribute("userDetails", user);
				forword = "redirect:dashboard";
			} catch (AuthenticationException e) {
				String errorMessage = applicationContext.getMessage("loginError", null, Locale.getDefault());
				result.reject(errorMessage, errorMessage);
				model.addAttribute("result", result);
				forword = "login";
			}
		} else {
			forword = "redirect:start";
		}
		}
		else{
			String errorMessage = applicationContext.getMessage("loginError", null, Locale.getDefault());
			result.reject(errorMessage, errorMessage);
			forword = "login";
		}
		return forword;
	}
	
	
	/**
	 * Logout.
	 *
	 * @param session the session
	 * @return the string
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		if (null == session.getAttribute("userDetails")) {return "redirect:login";}
		SecurityUtils.getSubject().logout();
		return "redirect:/";
	}
}
